package com.wgc.order.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.wgc.ALpay.domain.AliPay;
import com.wgc.ALpay.feign.PayFeign;
import com.wgc.order.config.RabbitConfig;
import com.wgc.order.domain.Order;
import com.wgc.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class PayListener {
    @Autowired
    private PayFeign payFeign;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitConfig.PAY_DEAD_QUEUE)
    public void pay(String orderStr) {
        //格式转换
        Order param = JSONObject.parseObject(orderStr, Order.class);
        //查询出数据库订单状态
        Order orderSelect = new Order();
        orderSelect.setId(param.getId());
        Order order = orderService.selectList(orderSelect).get(0);
        //如果不是未支付，说明已经走过回调了
        if (order.getStatus() != 0) {
            return;
        }
        //如果是未支付，调用支付模块查询支付状态
        AliPay aliPay = new AliPay();
        aliPay.setTime(order.getCreateTime().getTime());
        Map query = payFeign.queryPayment(aliPay);
        //如果支付成功，修改订单状态
        if (query.get("msg").equals("Success")) {
            //成功订单补偿
            order.setTradeNo(query.get("trade_no").toString());
            order.setStatus(2);
        }else {
            //失败订单补偿
            order.setStatus(7);
            //回滚库存
            rabbitTemplate.convertAndSend("",RabbitConfig.ADD_QUEUE, JSON.toJSONString(order));
        }
        orderService.update(order);

    }
    @RabbitListener(queues = RabbitConfig.RECEIVING_QUEUE)
    public void RECEIVING_QUEUE(String message){
        List<Order> list = JSONObject.parseObject(message, List.class);
        for (Order order : list) {
            Order select = new Order();
            select.setId(order.getId());
            //进行状态校验
            order = orderService.selectList(select).get(0);
            if (order.getStatus() == 6) {
                return;
            }
            if (order.getStatus() != 3) {
                throw new RuntimeException("订单状态异常");
            }
            order.setStatus(6);
            order.setUpdateTime(new Date());
            orderService.update(order);
        }
    }

}
